from django.shortcuts import render,HttpResponse,redirect
from app01 import models
from django import forms
from django.core.exceptions import ValidationError
from django.urls import reverse
# Create your views here.
def lad(request):
    lad_all=models.Lad.objects.all()
    return render(request,'lad_list.html',{'lad_all':lad_all})
def matter (request):
    matter_all=models.Matter.objects.all()
    return render(request,'matter_list.html',{'matter_all':matter_all})
def user(request):
    user_all=models.User.objects.all()
    return render(request,'user_list.html',{'user_all':user_all})




class RegForm(forms.Form):
#局部钩子
    def clean_room(self):
        value =self.cleaned_data.get('room')
        if models.Lad.objects.filter(room=value):
            raise ValidationError('班级已存在')
        if value[0] != self.cleaned_data.get('floor'):
            raise ValidationError('班级设置不符合楼层数')
    def clean_l_name(self):
        value = self.cleaned_data.get('l_name')
        if models.Lad.objects.filter(l_name=value):
            raise ValidationError('实验室名称已存在')
    # 名称、楼层、房间号、负责人
    l_name = forms.CharField(
        label='名称',
        widget=forms.TextInput,
        min_length=3,
        # validators=[checkusername,],
        required=True,
    error_messages={'required':'该字段不能为空'}
    )
    floor =  forms.CharField(label='楼层',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    room =  forms.CharField(label='房间号',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    l_people =  forms.CharField(label='负责人',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
def add_lad(request):
    if request.method =='POST':
        form_obj=RegForm(request.POST)
        if form_obj.is_valid(): # 校验数据
            print(request.POST)
            models.Lad.objects.create(l_name=request.POST.get('l_name'),floor=request.POST.get('floor'),room=request.POST.get('room'),l_people=request.POST.get('l_people'))
            return redirect(reverse('lad_list'))
    else:
        form_obj=RegForm()
    return render(request,'add_lad.html',{'form_obj':form_obj})




#
# def add_lad(request):
#     pass


class RegForm1(forms.Form):
#局部钩子
    def clean_number(self):
        value =self.cleaned_data.get('number')
        if models.Matter.objects.filter(number=value):
            raise ValidationError('编号已存在')


    def clean_lad_id(self):
        value = self.cleaned_data.get('lad_id')
        if not models.Lad.objects.filter(l_name=value):
            raise ValidationError('实验室不存在')

    # 名称、编号、购买时间、所属实验室
    m_name = forms.CharField(
        label='名称',
        widget=forms.TextInput,
        # min_length=3,
        # validators=[checkusername,],
        required=True,
    error_messages={'required':'该字段不能为空'}
    )
    desc =  forms.CharField(label='物质描述',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    number =  forms.CharField(label='编号',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    time =  forms.CharField(label='购买时间',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    m_people =  forms.CharField(label='购买人',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    lad_id =  forms.CharField(label='所属实验室',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
def add_matter(request):
    if request.method =='POST':
        form_obj=RegForm1(request.POST)
        if form_obj.is_valid(): # 校验数据
            print(request.POST)
            lad_id=models.Lad.objects.filter(l_name = request.POST.get('lad_id')).values('pk').first().get('pk')
            models.Matter.objects.create(m_name=request.POST.get('m_name'),desc=request.POST.get('desc'),number=request.POST.get('number'),time=request.POST.get('time'),m_people=request.POST.get('m_people'),lad_id=lad_id)
            return redirect(reverse('matter_list'))
    else:
        form_obj=RegForm1()
    return render(request,'add_matter.html',{'form_obj':form_obj})
# def add_matter(request):
#     pass

class RegForm2(forms.Form):
#局部钩子
    def clean_u_name(self):
        value =self.cleaned_data.get('u_name')
        if models.User.objects.filter(u_name=value):
            raise ValidationError('用户已存在')
    def clean_lad_id(self):
        value = self.cleaned_data.get('lad_id')
        if not models.Lad.objects.filter(l_name=value):
            raise ValidationError('实验室不存在')
# 名称、楼层、房间号、负责人
    u_name = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        min_length=3,
        # validators=[checkusername,],
        required=True,
    error_messages={'required':'该字段不能为空'}
    )
    password =  forms.CharField(label='密码',widget=forms.PasswordInput,error_messages={'required':'该字段不能为空'})#插件
    name =  forms.CharField(label='姓名',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
    phone =  forms.CharField(label='手机号',widget=forms.TextInput,error_messages={'required':'该字段不能为空'},min_length=11,max_length=11)#插件
    lad_id =  forms.CharField(label='使用实验室',widget=forms.TextInput,error_messages={'required':'该字段不能为空'})#插件
def add_user(request):
    if request.method =='POST':
        form_obj=RegForm2(request.POST)
        if form_obj.is_valid(): # 校验数据
            print(request.POST)
            lad_id = models.Lad.objects.filter(l_name=request.POST.get('lad_id')).values('pk').first().get('pk')
            models.User.objects.create(u_name=request.POST.get('u_name'),password=request.POST.get('password'),name=request.POST.get('name'),phone=request.POST.get('phone'),lad_id=lad_id)
            return redirect(reverse('user_list'))
    else:
        form_obj=RegForm2()
    return render(request,'add_user.html',{'form_obj':form_obj})
# def add_user(request):
#     pass
def exit_lad(request,pk):
    error = ''
    error1 = ''
    error2 = ''
    error3 = ''
    error4 = ''
    # get 请求
    # 获取要编辑对象的ID



    lad = models.Lad.objects.filter(pk=pk)  # 对象列表
    if not lad:
        return HttpResponse('数据不存在')
    # 获取对象pk
    lad_obj = lad[0]
    if request.method == 'POST':
        # 获取新提交的数据
        l_name = request.POST.get('l_name')
        floor = request.POST.get('floor')
        room = request.POST.get('room')
        l_people = request.POST.get('l_people')
        # 对用户提交的数据进行校验
        if not l_name:
            # 出版社名称为空
            error = '实验室名称不能为空'
        elif lad_obj.l_name != l_name and models.Lad.objects.filter(l_name=l_name):
            # 出版社名称重复
            error1 = '实验室名称已存在'
        elif not room:
            error3="房间号不能为空"
        elif str(floor) != str(room)[0]:
            print(str(lad_obj.floor),type(str(lad_obj.floor) ))
            print(str(lad_obj.room)[0],type(str(lad_obj.room)[0]))
            error2 = '房间号不符合要求'
        elif not l_people:
            error4="购买人不能为空"
        else:
            # 修改数据
            lad_obj.l_name = l_name
            lad_obj.floor = floor
            lad_obj.room = room
            lad_obj.l_people = l_people
            lad_obj.save()  # 将修改提交的数据库
            # 跳转到展示页面
            return redirect(reverse('lad_list'))
    # 返回一个页面进行展示
    return render(request, 'exit_lad.html',{'lad_obj':lad_obj ,'error':error,'error1':error1,'error2':error2,'error3':error3,'error4':error4} )


def exit_matter(request,pk):

    error1 = ''
    error2 = ''
    error3 = ''
    error4 = ''
    error5 = ''
    error6 = ''
    error7 = ''

    # get 请求
    # 获取要编辑对象的ID

    matter = models.Matter.objects.filter(pk=pk)  # 对象列表
    if not matter:
        return HttpResponse('数据不存在')
    # 获取对象pk
    matter_obj = matter[0]
    if request.method == 'POST':
        # 获取新提交的数据
        m_name = request.POST.get('m_name')
        desc = request.POST.get('desc')
        number = request.POST.get('number')
        time = request.POST.get('time')
        m_people = request.POST.get('m_people')
        if not m_name:
            error3="器材名不能为空"
        elif not desc:
            error4='介绍不能为空'
        elif not number:
            error5="编号不能为空"
        elif not time:
            error6 = "时间不能为空"
        elif not m_people:
            error7 = "购买人不能为空"
        elif models.Lad.objects.filter(l_name=request.POST.get('lad_id')) and request.POST.get('lad_id') !=matter_obj.lad.l_name :
            error1="实验室已存在，改别的名"
        elif not models.Lad.objects.filter(l_name=request.POST.get('lad_id')):
            lad_obj=models.Lad.objects.get(pk=matter_obj.lad_id)
            lad_obj.l_name=request.POST.get('lad_id')
            lad_obj.save()
        # 对用户提交的数据进行校验
        elif str(matter_obj.number) != number and models.Matter.objects.filter(number=number):

            error2 = '器材编号已存在'
        else:
            # 修改数据
            matter_obj.m_name = m_name
            matter_obj.desc = desc
            matter_obj.number = number
            matter_obj.time = time
            matter_obj.m_people = m_people
            matter_obj.lad_id = matter_obj.lad_id
            matter_obj.save()  # 将修改提交的数据库
            # 跳转到展示页面
            return redirect(reverse('matter_list'))
    # 返回一个页面进行展示
    return render(request, 'exit_matter.html', {'matter_obj': matter_obj,  'error1': error1, 'error2': error2, 'error3': error3, 'error4': error4, 'error5': error5, 'error6': error6, 'error7': error7})
from django.http import JsonResponse

def exit_user(request,pk):
    error1=""
    error2=""
    error3=""
    error4=""
    error5=""
    error6=""
    error7=""
    user = models.User.objects.filter(pk=pk)
    if not user:
        return HttpResponse('数据不存在')
    # 获取对象pk
    user_obj = user[0]
    if request.method =="POST":
        u_name = request.POST.get('u_name')
        password = request.POST.get('password')
        name = request.POST.get('name')
        phone = request.POST.get('phone')
        lad_id = request.POST.get('lad_id')
        # print(models.User.objects.filter(u_name=request.POST.get('u_name')) and request.POST.get('u_name') !=user_obj.u_name)
        if not u_name:
            error3="用户名不能为空"
        elif not password:
            error4="密码不能为空"
        elif not name:
            error5="姓名不能为空"
        elif not phone:
            error6="电话不能为空"
        elif not lad_id:
            error7="实验室不能为空"
        elif models.User.objects.filter(u_name=request.POST.get('u_name')) and request.POST.get('u_name') !=user_obj.u_name :

            error1="用户名已存在，改别的名"
        # print(models.Lad.objects.filter(l_name=request.POST.get('lad_id')) and request.POST.get('lad_id') !=user_obj.lad.l_name )
        elif models.Lad.objects.filter(l_name=request.POST.get('lad_id')) and request.POST.get('lad_id') !=user_obj.lad.l_name :
             error2="实验室已存在，改别的名"
        # print(not models.Lad.objects.filter(l_name=request.POST.get('lad_id')))
        elif not models.Lad.objects.filter(l_name=request.POST.get('lad_id')):
            lad_obj=models.Lad.objects.get(pk=user_obj.lad_id)
            lad_obj.l_name=request.POST.get('lad_id')
            lad_obj.save()
        else:
            user_obj.u_name =u_name
            user_obj.password =password
            user_obj.name = name
            user_obj.phone = phone
            user_obj.lad_id = user_obj.lad_id
            user_obj.save()
            return redirect(reverse('user_list'))
    return render(request,'exit_user.html',{"user_obj":user_obj,'error1':error1,'error2':error2,'error3':error3,'error4':error4,'error5':error5,'error6':error6,'error7':error7})



def del_matter(request):
    pid = request.GET.get('p_id')
    ret = models.Matter.objects.filter(pk=pid)
    if not ret:
        return HttpResponse('数据不存在')

    # 从数据库删除数据
    ret.delete()  # 对象列表 删除
    return JsonResponse({'status': 200, 'msg': 'ok'})

def del_lad(request):
    pid = request.GET.get('p_id')
    ret = models.Lad.objects.filter(pk=pid)
    if not ret:
        return HttpResponse('数据不存在')

    # 从数据库删除数据
    ret.delete()  # 对象列表 删除
    return JsonResponse({'status': 200, 'msg': 'ok'})

def del_user(request):
    pid = request.GET.get('p_id')
    ret = models.User.objects.filter(pk=pid)
    if not ret:
        return HttpResponse('数据不存在')

    # 从数据库删除数据
    ret.delete()  # 对象列表 删除
    return JsonResponse({'status': 200, 'msg': 'ok'})
